import React, { useState, useEffect } from 'react';
import { Card, Input, Select, Button, message, Form, Space, Spin, Typography, Modal } from 'antd';
import { getExpires, editExpires } from '@/utils/api/system/system';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { Option } = Select;
const { Text } = Typography;
const { confirm } = Modal;

const Expires: React.FC = () => {
    const [form] = Form.useForm();
    const [currentExpires, setCurrentExpires] = useState<string>('');
    const [loading, setLoading] = useState<boolean>(true);
    const [submitting, setSubmitting] = useState<boolean>(false);

    // 解析冷却期字符串
    const parseExpires = (expiresStr: string) => {
        const regex = /^(\d+)([dhms]|ms)$/i;
        const match = expiresStr.match(regex);

        if (!match) return { value: 0, unit: 'd' };

        return {
            value: parseInt(match[1], 10),
            unit: match[2].toLowerCase()
        };
    };

    // 获取当前冷却期设置
    const fetchExpires = async () => {
        try {
            setLoading(true);
            const data = await getExpires();
            setCurrentExpires(data);

            const parsed = parseExpires(data);
            form.setFieldsValue({
                value: parsed.value,
                unit: parsed.unit
            });
        } catch (error) {
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    // 提交新的冷却期设置
    const handleSubmit = async (values: { value: number; unit: string }) => {
        try {
            setSubmitting(true);
            const newExpires = `${values.value}${values.unit}`;
            await editExpires(newExpires);
            setCurrentExpires(newExpires);
            message.success('冷却期设置更新成功');
        } catch (error) {
            console.error(error);
        } finally {
            setSubmitting(false);
        }
    };

    // 将单位转换为可读文本
    const getUnitText = (unit: string) => {
        switch (unit) {
            case 'd': return '天';
            case 'h': return '小时';
            case 'm': return '分钟';
            case 's': return '秒';
            case 'ms': return '毫秒';
            default: return unit;
        }
    };

    // 显示确认对话框
    const showConfirm = (values: { value: number; unit: string }) => {
        confirm({
            title: '确认更新冷却期设置',
            icon: <ExclamationCircleOutlined />,
            content: `您确定要将冷却期设置为 ${values.value} ${getUnitText(values.unit)} 吗？`,
            onOk() {
                return handleSubmit(values);
            },
            onCancel() {
                console.log('取消更新');
            },
        });
    };

    useEffect(() => {
        fetchExpires();
    }, []);

    return (
        <Card title="冷却期设置" style={{ maxWidth: 600 }}>
            <Spin spinning={loading}>
                {currentExpires && (
                    <div style={{ marginBottom: 24 }}>
                        <Text>当前冷却期: </Text>
                        <Text strong>
                            {parseExpires(currentExpires).value}
                            {getUnitText(parseExpires(currentExpires).unit)}
                        </Text>
                    </div>
                )}

                <Form
                    form={form}
                    layout="inline"
                    onFinish={showConfirm}
                >
                    <Form.Item
                        name="value"
                        label="时长"
                        rules={[
                            { required: true, message: '请输入时长' },
                            { pattern: /^[1-9]\d*$/, message: '请输入正整数' }
                        ]}
                    >
                        <Input type="number" min={1} style={{ width: 100 }} />
                    </Form.Item>

                    <Form.Item
                        name="unit"
                        label="单位"
                        rules={[{ required: true, message: '请选择单位' }]}
                    >
                        <Select style={{ width: 100 }}>
                            <Option value="d">天</Option>
                            <Option value="h">小时</Option>
                            <Option value="m">分钟</Option>
                            <Option value="s">秒</Option>
                            <Option value="ms">毫秒</Option>
                        </Select>
                    </Form.Item>

                    <Form.Item>
                        <Space>
                            <Button
                                type="primary"
                                htmlType="submit"
                                loading={submitting}
                            >
                                更新设置
                            </Button>
                            <Button onClick={() => form.resetFields()}>
                                重置
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Spin>
        </Card>
    );
};

export default Expires;